document.addEventListener("DOMContentLoaded", function () {
    const settingsToggle = document.getElementById("settings-toggle");
    const settingsContent = document.getElementById("settings-content");
    const addressSelect = document.getElementById("address");
    const modelSelect = document.getElementById("model");
    const temperatureInput = document.getElementById("temperature");
    const temperatureValue = document.getElementById("temperature-value");
    const newChatButton = document.getElementById("new-chat");
    const saveChatButton = document.getElementById("save-chat");
    const historyList = document.getElementById("history-list");
    const chatWindow = document.getElementById("chat-window");
    const userInput = document.getElementById("user-input");
    const submitButton = document.getElementById("submit-button");

    const ADDRESSES = {
        "Ollama": {
            "base_url": "http://localhost:11434/v1",
            "models": [ "qwen2.5:3b", "glm4", "llama3.2", "phi", "phi3", "deepseek-r1:1.5b", "mistral:7b-instruct-q2_k"]
        },
        "LMstudio": {
            "base_url": "http://localhost:12345/v1",
            "models": ["qwen2.5-instructv2-7b", "qwen-chatv2-7b", "deepseek-r1-qwen-7b"]
        },
        "AiGitee": {
            "base_url": "https://ai.gitee.com/api/v1",
            "models": [
                "Qwen2-7B-Instruct", "Qwen2.5-72B-Instruct", "Qwen2.5-14B-Instruct", "Qwen2.5-7B-Instruct",
                "Qwen2-72B-Instruct", "Qwen2-7B-Instruct", "Qwen2-32B-Instruct", "QwQ-32B-Preview", "Yi-34B-Chat", "glm-4-9b-chat"
            ]
        },
        "ChatGLM": {
            "base_url": "https://open.bigmodel.cn/api/paas/v4",
            "models": ["glm-4-flash"]
        },
        "THUds": {
            "base_url": "https://madmodel.cs.tsinghua.edu.cn/v1",
            "models": ["DeepSeek-R1-Distill-32B", "DeepSeek-R1-671B"]
        }
    };

    let currentConversation = [];
    let currentConversationTitle = null;
    let chatHistory = [];

    // 初始化设置
    settingsToggle.addEventListener("click", () => {
        settingsContent.classList.toggle("hidden");
    });

    addressSelect.addEventListener("change", () => {
        const selectedAddress = addressSelect.value;
        const models = ADDRESSES[selectedAddress].models;
        modelSelect.innerHTML = models.map(model => `<option value="${model}">${model}</option>`).join("");
    });

    temperatureInput.addEventListener("input", () => {
        temperatureValue.textContent = temperatureInput.value;
    });

    // 初始化模型列表
    addressSelect.dispatchEvent(new Event("change"));
    submitButton.disabled = false;
    userInput.disabled = false;

    // 确保renderChatWindow函数存在（补充缺失部分）
    function renderChatWindow() {
        try {
            chatWindow.innerHTML = chatHistory.map(msg => `
                <div class="message ${msg.role}">
                    ${msg.content.replace(/\n/g, '<br>')}
                </div>
            `).join("");
            
            // 添加平滑滚动动画
            chatWindow.scrollTo({
                top: chatWindow.scrollHeight,
                behavior: 'smooth'
            });
        } catch (error) {
            console.error("渲染聊天窗口时发生错误:", error);
            chatWindow.innerHTML = `<div class="error">⚠️ 消息渲染失败: ${error.message}</div>`;
        }
    }

    // 强化后的loadHistory函数
    function loadHistory() {
        try {
            const rawHistory = localStorage.getItem("chatHistory");
            if (!rawHistory) {
                historyList.innerHTML = '<li class="first-child">暂无历史记录</li>';
                return;
            }

            const history = JSON.parse(rawHistory);
            if (!Array.isArray(history)) {
                throw new Error("历史记录格式错误");
            }

            historyList.innerHTML = history
                .sort((a, b) => new Date(b.time) - new Date(a.time))
                .map((conv, index) => `
                    <li data-index="${index}">
                        <strong>${conv.title || '未命名会话'}</strong>
                        <small>${new Date(conv.time).toLocaleString()}</small>
                    </li>
                `).join("");

            // 绑定点击事件
            document.querySelectorAll('#history-list li').forEach(li => {
                li.addEventListener('click', async () => {
                    try {
                        const index = li.dataset.index;
                        const history = JSON.parse(localStorage.getItem("chatHistory"));
                        
                        if (currentConversation.length > 0) {
                            await saveCurrentConversation();
                        }

                        const selectedConv = history[index];
                        if (!selectedConv.messages) {
                            throw new Error("会话数据损坏");
                        }

                        currentConversation = [...selectedConv.messages];
                        chatHistory = [...selectedConv.messages];
                        renderChatWindow();
                    } catch (error) {
                        alert(`加载会话失败: ${error.message}`);
                        loadHistory(); // 重新加载清理损坏数据
                    }
                });
            });

        } catch (error) {
            console.error("加载历史记录失败:", error);
            historyList.innerHTML = `
                <li class="error">
                    ⚠️ 历史记录加载失败
                    <small>${error.message}</small>
                </li>
            `;
            
            // 尝试恢复默认状态
            localStorage.removeItem("chatHistory");
            currentConversation = [];
            chatHistory = [];
        } finally {
            // 确保始终显示最新状态
            historyList.style.opacity = 1;
            document.querySelector('.history-card').classList.remove('loading');
        }
    }


    // 新建会话
    newChatButton.addEventListener("click", () => {
        if (currentConversation.length > 0) {
            const title = `${currentConversation[1].content.substring(0, 10)} - ${new Date().toLocaleString()}`;
            saveConversation(title, currentConversation);
        }
        currentConversationTitle = null;
        currentConversation = [];
        chatHistory = [];
        submitButton.disabled = false;
        userInput.disabled = false;
        renderChatWindow(); // 清空聊天区
        loadHistory();      // 刷新历史记录
    });

    // 保存对话为 CSV 文件（兼容中文）
    saveChatButton.addEventListener("click", () => {
        if (chatHistory.length === 0) {
            alert("没有可保存的对话内容！");
            return;
        }
        const csvContent = "角色,内容\n" + chatHistory.map(msg => `${msg.role},${msg.content}`).join("\n");
        const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" }); // 添加 BOM 头
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "chat_history.csv";
        a.click();
        URL.revokeObjectURL(url);
    });

    // 在saveConversation函数中修改时间存储格式
    function saveConversation(title, messages) {
        const history = JSON.parse(localStorage.getItem("chatHistory") || []);
        alert(`chatHistory:${history}`)
        history.push({
            title,
            time: new Date().toISOString(),  // 改用ISO格式存储
            messages: [...messages]          // 深拷贝避免引用问题
        });
        localStorage.setItem("chatHistory", JSON.stringify(history));
        // alert(`"${title}" 已保存`)
        loadHistory();
    }

    // 提取保存当前会话的逻辑
    async function saveCurrentConversation() {
        return new Promise(resolve => {
            const firstUserMessage = currentConversation.find(msg => msg.role === 'user');
            const title = firstUserMessage 
                ? `${firstUserMessage.content.substring(0, 15)}...`
                : `未命名会话-${new Date().getTime()}`;
            
            saveConversation(title, currentConversation);
            resolve();
        });
    }

    // 修改新建会话按钮逻辑
    newChatButton.addEventListener("click", async () => {
        if (currentConversation.length > 0) {
            await saveCurrentConversation();
        }
        currentConversationTitle = null;
        currentConversation = [];
        chatHistory = [];
        renderChatWindow();
    });

    // 修改消息提交逻辑（添加自动标题生成）
    function submitMessage() {
        const userMessage = userInput.value;
        if (!userMessage) return;

        // 禁用按钮和输入框
        submitButton.disabled = true;
        // userInput.disabled = true;

        currentConversation.push({ role: "user", content: userMessage });
        chatHistory.push({ role: "user", content: userMessage });
        renderChatWindow();

        const payload = {
            model: modelSelect.value,
            messages: currentConversation,
            // stream: true,
            stream:false,
            temperature: parseFloat(temperatureInput.value)
        };

        const headers = {
            "Authorization": `Bearer ${document.getElementById("api-key").value}`,
            "Content-Type": "application/json"
        };

        fetch(`${ADDRESSES[addressSelect.value].base_url}/chat/completions`, {
            method: "POST",
            headers: headers,
            body: JSON.stringify(payload)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`API 响应失败! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                const assistantMessage = data.choices[0].message.content;
                // alert(`assistantMessage:${assistantMessage}`)  //LLM可以正常返回response

                // 自动生成标题（当第一次收到回复时）
                if (currentConversation.length === 1) {  // 用户消息是第0条
                    currentConversationTitle = `${userMessage.substring(0, 12)}...`;  // 自动生成标题，至少6个字？
                    // alert(`currentConversationTitle:${currentConversationTitle}`)  //LLM可以正常返回response
                    document.querySelector('#history-list li:first-child').textContent = currentConversationTitle;
                }
                
                currentConversation.push({ role: "assistant", content: assistantMessage });
                chatHistory.push({ role: "assistant", content: assistantMessage });
                renderChatWindow();
            })
            .catch(error => {
                console.error("请求发送失败:", error);
                alert(`请求发送失败: ${error.message}`);
            })
            .finally(() => {
                // 无论成功与否，重新启用
                submitButton.disabled = false;
                // userInput.disabled = false;
            });

        userInput.value = "";
    }

    // 提交按钮和回车键事件
    submitButton.addEventListener("click", submitMessage);    
    userInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
            submitMessage();
        }
    });

    // 初始化加载历史记录
    loadHistory();
});